import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;

public class FileInputStreamDemo {
    //通过read()方法读取文件内容
    public static void read1(){
       //try-with-source写法
        try(InputStream inputStream=new FileInputStream("D:/temp/java.txt")){
             while(true){
                 int n=inputStream.read();
                 if(n==-1){
                     break;
                 }
                 System.out.println((char)n);//记得转换为char类型，不然是ASCII码值

             }

        }catch(IOException e){
            throw new RuntimeException(e);
        }

    }

    //
    public static void read2(){
        try(InputStream inputStream=new FileInputStream("D:/temp/java.txt")){
            byte[] buf=new byte[1024];
            while(true){
                int num=inputStream.read(buf);
                if(num==-1){
                    break;
                }
                for(int i=0;i<num;i++){
                    System.out.println((char)buf[i]);
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void read3(){
        try(InputStream inputStream=new FileInputStream("D:/temp/java.txt")){
            byte[] buf=new byte[1024];
            while(true){
                int num=inputStream.read(buf);
                if(num==-1){
                    break;
                }
                for(int i=0;i<num;i+=3){ //3个3个的读取
                    System.out.println(new String(buf,i,3));
                }
            }

        }catch(Exception e){
            e.printStackTrace();
        }
    }
    //利用Scanner读取
    public static void read4(){

        try(InputStream inputStream=new FileInputStream("D:/temp/java.txt")){
            Scanner sc=new Scanner(inputStream);
            while(sc.hasNext()){
                //一行一行的读取
                String str=sc.nextLine();
                System.out.println(str);
            }
        }catch(Exception e){
            e.printStackTrace();

        }

    }
    public static void main(String[] args) {
        read4();

    }
}
